<template>
  <VPage>
    <VTable ref="tableRef" v-bind="tableOptions" @header-cell-click="headerCellClickEvent">
      <template #form="{ form }">
        <VSelect v-model="form.platform_ids" placeholder="平台" :options="options.platform" multiple collapse-tags
          style="min-width: 160px" />
        <VSelect v-model="form.shop_ids" placeholder="店铺" :options="options.shop" multiple collapse-tags
          style="min-width: 160px" confusedPaste paste />
        <VSelect v-model="form.vat_ids" placeholder="VAT" :options="options.vat" multiple collapse-tags
          style="min-width: 160px" />
        <VSelect v-model="form.epr_ids" placeholder="EPR" :options="options.epr" multiple collapse-tags
          style="min-width: 160px" />
        <VCascader v-model="form.province_ids" placeholder="省份" type="3" multiple style="min-width: 160px" />
        <VCascader v-model="form.create_ids" placeholder="创建人" multiple collapse-tags style="min-width: 160px" />
        <VSelect v-model="form.statuses" placeholder="状态" :options="options.status" multiple collapse-tags
          style="min-width: 160px" />
        <VGroup>
          <el-select v-model="form.dateRange.type" style="width: 100px">
            <el-option label="创建日期" value="create_time"></el-option>
            <el-option label="成立时间" value="established_date"></el-option>
          </el-select>
          <el-date-picker v-model="form.dateRange.value" type="daterange" value-format="YYYY-MM-DD" range-separator="至"
            start-placeholder="开始日期" end-placeholder="结束日期" style="max-width: 260px" />
        </VGroup>
        <VGroup>
          <el-select v-model="form.input.type" style="width: 110px">
            <el-option label="公司名称" value="company_name_ch"></el-option>
            <el-option label="法人手机号" value="legal_person_mobile"></el-option>
            <el-option label="法人" value="legal_person_name"></el-option>
            <el-option label="营业执照号" value="license_num"></el-option>
          </el-select>
          <el-input v-model="form.input.value" placeholder="请输入" class="w-60" />
        </VGroup>
      </template>
      <template #toolbar_btns>
        <VButton auth="/base/company/create" type="primary" icon="DocumentAdd" @click="create(tableRef)">添加</VButton>
        <VButton auth="/base/company/delete" @click="handleBatch('delete')">删除</VButton>
        <VImport :tableRef="tableRef" importUrl="/v1/company/import"
          downloadUrl="https://xc-base.oss-cn-shenzhen.aliyuncs.com/template/company.xlsx" class="ml-auto" />
        <VExport auth="/base/company/export" mainKey="company_id" name="company" :tableRef="tableRef" task />
      </template>
    </VTable>
    <Add ref="addRef" :options="options" @success="query" />
    <VLog ref="logRef" />
    <Bind ref="bindRef" />
    <BindVAT ref="bindRefVAT" />
    <BindEPR ref="bindRefEPR" />
  </VPage>
</template>
  
<script setup lang="jsx" name="Account">
import api from './api'
import Add from './components/Add'
import Bind from './components/Bind'
import VImport from '@/components/VImport'
import { getOption } from '@/api/public'
import { ElMessage, ElMessageBox } from 'element-plus'
import BindVAT from "./components/BindVAT/index.vue";
import BindEPR from "./components/BindEPR/index.vue";

const baseName = 'company'
const tableRef = ref()
const logRef = ref()
const loadings = reactive({})
// 查询
const query = () => {
  tableRef?.value.query()
}

// 新增
const addRef = ref()
const create = () => {
  addRef?.value.open()
}

// 获取options
const options = ref({})
Promise.all([
  getOption({ type: baseName }).then(res => res.data),
  Promise.resolve({ test: [{ label: '没有数据', value: 1 }] })
]).then(res => {
  options.value = res.reduce((acc, cur) => (((acc = { ...acc, ...cur }), acc)), {})
})

const authList = window.BTN_AUTH || []

const authInnerColumn = {
  bind: authList.includes('/base/company/shop-list'),
  bindRefVAT: authList.includes('/base/company/vat-list'),
  bindRefEPR: authList.includes('/base/company/epr-list'),
}
console.error('authInnerColumn', authInnerColumn)



// 批量操作
const handleBatch = (name) => {
  const selection = tableRef.value.$table.getCheckboxRecords()
  if (!selection.length) {
    ElMessage.warning('请先选择行')
    return
  }
  const company_ids = selection.map(d => d.company_id)
  const showLoading = () => loadings[name] = true
  const closeLoading = () => loadings[name] = false
  const handle = {
    delete: () => {
      ElMessageBox.confirm('是否确认删除？', '删除', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
      })
        .then(() => {
          showLoading()
          api.delete({ company_ids }).then(res => {
            ElMessage({ type: 'success', message: '操作成功', })
            query()
          }).finally(closeLoading)
        })
        .catch(() => {
          ElMessage({ type: 'info', message: '取消操作', })
        })
    },
  }
  handle[name]()
}
// 单行操作
const bindRef = ref()
const bindRefVAT = ref()
const bindRefEPR = ref()
const handleRow = (name, row, rowIndex) => {
  const { company_id } = row
  const showLoading = (name = 'handle') => {
    loadings[name + rowIndex] = true
  }
  const closeLoading = (name = 'handle') => {
    loadings[name + rowIndex] = false
  }
  const handle = {
    edit: () => {
      addRef?.value.open(company_id)
    },
    delete: () => {
      ElMessageBox.confirm('是否确认删除？', '删除', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
      })
        .then(() => {
          showLoading()
          api.delete({ company_ids: [company_id] }).then(res => {
            ElMessage({ type: 'success', message: '操作成功', })
            query()
          }).finally(closeLoading)
        })
        .catch(() => {
          ElMessage({ type: 'info', message: '取消操作', })
        })
    },
    bind: () => {
      bindRef?.value.open(company_id)
    },
    log: () => {
      logRef?.value.open({ type: baseName, record_id: company_id })
    },
  }
  handle[name]()
}

const handleBindDialog = (row, type) => {
  const { company_id } = row
  switch (type) {
    case 'bindRefVAT':
      bindRefVAT?.value.open(company_id)
      break;
    case 'bindRefEPR':
      bindRefEPR?.value.open(company_id)
      break;
    default:
      break;
  }
}

// 列表配置
const tableOptions = reactive({
  rowConfig: { height: 74 },
  showHeaderOverflow: false,
  formConfig: {
    data: {
      input: { type: 'company_name_ch', value: '' }, // 组合
      dateRange: { type: 'create_time', value: [], range: true }, // 组合
    }
  },
  columns: [
    { type: 'checkbox', fixed: 'left', width: 40 },
    { field: 'company_id', fixed: 'left', width: 70, sortable: true, slots: { header: () => '序号'} },
    {
      field: '', minWidth: 220, slots: {
        header: [
          {title: '公司名称', sort: 'company_name_ch'},
          {title: '营业执照号', sort: 'license_num'},
          {title: '成立时间', sort: 'established_date'},
        ],
        default: ({ row }) => < div >
          <VText value={row.company_name_ch} />
          <VText value={row.license_num} />
          <VText value={row.established_date} />
        </div >
      }
    },
    {
      field: '', minWidth: 180, slots: {
        header: [
          {title: '法人', sort: 'legal_person_name'},
          {title: '身份证号', sort: 'legal_person_idcard'},
          {title: '手机号', sort: 'legal_person_mobile'},
        ],
        default: ({ row }) => < div >
          <VText value={row.legal_person_name} />
          <VText value={row.legal_person_idcard} />
          <VText value={row.legal_person_mobile} />
        </div >
      }
    },
    {
      title: '省份/城市', field: 'company_area_names', minWidth: 140, sortable: true, slots: {
        default: ({ row }) => <VText value={row.company_area_names.replaceAll(',', ' ')} line={3} />
      }
    },
    {
      title: '公司地址', field: 'company_address_detail', minWidth: 140, sortable: true, slots: {
        default: ({ row }) => <VText value={row.company_address_detail} line={3} />
      }
    },
    { title: '邮编', field: 'postal_code', minWidth: 90, sortable: true },
    {
      title: '已注册平台', field: 'registereds', minWidth: 140, sortable: true, slots: {
        default: ({ row }) => <VText value={row.registereds} line={3} />
      }
    },
    {
      title: '状态', field: 'status', minWidth: 80, sortable: true
    },
    {
      field: '', minWidth: 180, slots: {
        header: [
          {title: '对公账号', sort: 'public_bank'},
          {title: '支行', sort: 'bank_branch'},
          {title: '卡号', sort: 'bank_account_num'},
        ],
        default: ({ row }) => < div>
          <VText value={row.public_bank} />
          <VText value={row.bank_branch} />
          <VText value={row.bank_account_num} />
        </div >
      }
    },
    {
      title: '关联店铺', minWidth: 100, field: 'assoc_shops', sortable: true, slots: {
        default: ({ row }) => row.assoc_shops ? (authInnerColumn.bind ? <el-button link type='primary' onClick={() => handleRow('bind', row)}>{row.assoc_shops}</el-button> : row.assoc_shops) : 0
      }
    },
    {
      title: '关联VAT', field: 'assoc_vats', minWidth: 100, sortable: true, slots: {
        default: ({ row }) => row.assoc_vats ? (authInnerColumn.bindRefVAT ? <el-link onClick={() => handleBindDialog(row, 'bindRefVAT')} type='primary'>{row.assoc_vats}</el-link> : row.assoc_vats) : 0
      }
    },
    {
      title: '关联EPR', field: 'assoc_eprs', minWidth: 100, sortable: true, slots: {
        default: ({ row }) => row.assoc_eprs ? (authInnerColumn.bindRefEPR ? <el-link onClick={() => handleBindDialog(row, 'bindRefEPR')} type='primary'>{row.assoc_eprs}</el-link> : row.assoc_eprs) : 0
      }
    },
    { title: '创建人', field: 'create_user', minWidth: 120, sortable: true },
    { title: '创建日期', field: 'create_time', minWidth: 170, sortable: true },
    {
      title: '备注', field: 'remark', minWidth: 120, slots: {
        default: ({ row }) => <VText value={row.remark} line={3} />
      }
    },
    {
      title: '操作', width: 110, fixed: 'right', slots: {
        default: ({ row, rowIndex }) => {
          return <div class='nm flex flex-wrap gap-1'>
            <VButton auth="/base/company/edit" link type="primary" onClick={() => handleRow('edit', row)}>编辑</VButton>
            <VButton auth="/base/company/delete" link type="danger" onClick={() => handleRow('delete', row, rowIndex)}>删除</VButton>
            <VButton auth="/base/company/log" link type="primary" onClick={() => handleRow('log', row)} class='m-0'>日志</VButton>
          </div>
        }
      }
    }
  ],
  proxyConfig: {
    ajax: {
      query: ({ page, form, sort }) => {
        const { field, order } = sort
        return api.query({ ...form, ...page, [field]: order === 'null' ? 'desc' : order })
      }
    }
  }
})

const headerCellClickEvent = ({ column, triggerResizable, triggerSort, triggerFilter }) => {
  if (column.sortable && !(triggerResizable || triggerFilter)) {
    const { field, order } = column
    tableRef.value.$table.sort(field, order)
    tableRef?.value.query()
  }
}
</script>
  